import json
import datetime

from flask import Blueprint
from flask import request
from flask import Response

from sqlalchemy import Column, String, Integer
from flask_sqlalchemy import SQLAlchemy

from app.comm.db import db
from app.system import auth
from app.comm.db import jsonformater
from app.comm.pub import RestEntity
from app.comm.pub import class2dict

userservice = Blueprint('user', __name__, )


class DataResItem(db.Model):
    __tablename__ = 'sys_user'
    user_id = Column(Integer, primary_key=True)
    user_name = Column(String(80), unique=True, nullable=False)
    email = Column(String(120), unique=True, nullable=False)

    def as_dict(self):
        return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}

    def __repr__(self):
        return '<User %r>' % self.username


@userservice.route("/rest/system/user/login", methods=['POST', 'GET'])
def userLogin():
    print(request.data)
    logindata = json.loads(request.data)
    tmpuser = User.query.filter_by(user_name='管理员').first().as_dict()
    # dict1["email"]=tmpuser.email
    print(tmpuser)
    # 获取token/
    token = auth.encode_auth_token(logindata["username"], 10).decode()
    # jsonify
    # jsonify(RestEntity(0,0,tmpuser,"登陆成功！",token))


    result = RestEntity(0, 0, tmpuser, "登陆成功！", token)
    # print(json.dumps(class2dict(result)))
    return json.dumps(class2dict(result))


# return json.dumps(dict1)
@userservice.route("/rest/system/user/list", methods=['POST', 'GET'])
def userList():
    a = request.get_data()

    # dict1 = json.loads(a)
    tables = db.session.execute(
        "select user_id userId,dept_id deptId,login_name loginName,user_name userName,user_type userType,email,phonenumber,sex,avatar,status,remark,create_time createTime from sys_user").fetchall()
    datas = [dict(r) for r in tables]
    result = RestEntity(0, 0, datas, "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)

    # return json.dumps(dict1)


@userservice.route("/rest/system/user/edit", methods=['POST', 'GET'])
def userEdit():
    editdata = request.get_data()
    print(editdata)
    tmpuser = User.query.filter_by(user_name='管理员').first().as_dict()
    # dict1["email"]=tmpuser.email
    print(tmpuser)

    result = RestEntity(0, 0, tmpuser, "登陆成功！")
    return json.dumps(class2dict(result))

    # return json.dumps(dict1)


@userservice.route("/rest/system/user/remove", methods=['POST', 'GET'])
def userRemove():
    print(request.values)
    ids = request.values.get('ids')
    sql = "update  sys_user set del_flag=2 where user_id=" + ids
    print(sql)
    # dict1 = json.loads(a)
    intcount = db.session.execute(sql)
    db.session.commit()
    # datas= [dict(r) for r in tables]
    result = RestEntity(0, 0, intcount, "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)


@userservice.route("/rest/system/user/checkPhoneUnique", methods=['POST', 'GET'])
def checkPhoneUnique():
    # print(request.values)
    userId = request.values.get('userId')
    phonenumber = request.values.get('phonenumber')

    sql = "select count(*) from   sys_user where phonenumber=" + phonenumber + " and user_id<>'" + userId + "'"

    # dict1 = json.loads(a)
    datacount = db.session.execute(sql).first()
    print(datacount)

    # datas= [dict(r) for r in tables]
    result = RestEntity(-1, 0, datacount[0], "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)

    # return json.dumps(dict1)


@userservice.route("/rest/system/user/checkEmailUnique", methods=['POST', 'GET'])
def checkEmailUnique():
    # print(request.values)
    userId = request.values.get('userId')
    email = request.values.get('email')

    sql = "select count(*) from   sys_user where email='" + email + "' and user_id<>'" + userId + "'"

    # dict1 = json.loads(a)
    intcount = db.session.execute(sql).first()
    print(intcount)

    # datas= [dict(r) for r in tables]
    result = RestEntity(-1, 0, intcount[0], "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)

    # return json.dumps(dict1)
